import argparse
import asyncio
from pathlib import Path
from .core import AssetManager
from .config import ConfigManager
from loguru import logger

def setup_logger():
    """配置日志"""
    log_dir = Path.home() / ".bitget_tool" / "logs"
    log_dir.mkdir(exist_ok=True)
    logger.add(
        log_dir / "bitget_{time}.log",
        rotation="1 day",
        retention="7 days",
        level="INFO"
    )

async def main():
    parser = argparse.ArgumentParser(description="Bitget交易所资产管理工具")
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # 配置命令
    config_parser = subparsers.add_parser("config", help="配置API密钥")
    config_parser.add_argument("--file", type=str, help="API配置文件路径")
    
    # 提币命令
    withdraw_parser = subparsers.add_parser("withdraw", help="批量提币")
    withdraw_parser.add_argument("--file", type=str, required=True, help="提币地址CSV文件路径")
    
    # 归集命令
    collect_parser = subparsers.add_parser("collect", help="资产归集")
    collect_parser.add_argument("--target", type=str, required=True, help="目标账户ID")
    
    # 清算命令
    liquidate_parser = subparsers.add_parser("liquidate", help="自动清算")
    liquidate_parser.add_argument("--target", type=str, default="USDT", help="目标币种")
    liquidate_parser.add_argument("--slippage", type=float, default=0.1, help="滑点保护")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
        
    config = ConfigManager()
    
    if args.command == "config":
        if not args.file:
            logger.error("请指定配置文件路径")
            return
            
        api_key, api_secret, passphrase = config.load_api_config(args.file)
        if all([api_key, api_secret, passphrase]):
            config.save_api_key(api_key, api_secret, passphrase)
            logger.success("API配置导入成功")
        else:
            logger.error("配置文件格式错误")
            
    elif args.command == "withdraw":
        addresses = config.load_withdraw_addresses(args.file)
        if not addresses:
            logger.error("未找到有效的提币地址")
            return
            
        async with AssetManager() as manager:
            for addr in addresses:
                try:
                    result = await manager.batch_withdraw(
                        coin=addr['coin'],
                        addresses=[{"address": addr['address'], "chain": addr['chain']}],
                        amount=addr['amount']
                    )
                    
                    if result[0]["status"] == "success":
                        logger.success(f"提币成功: {addr['address']} - 订单ID: {result[0]['order_id']}")
                    else:
                        logger.error(f"提币失败: {addr['address']} - 错误: {result[0]['error']}")
                except Exception as e:
                    logger.error(f"提币失败: {addr['address']} - 错误: {str(e)}")
                    
    elif args.command == "collect":
        async with AssetManager() as manager:
            results = await manager.collect_assets(args.target)
            
            for coin, transfers in results.items():
                for transfer in transfers:
                    if transfer["status"] == "success":
                        logger.success(f"划转成功: {coin} - 从 {transfer['from']} 划转 {transfer['amount']}")
                    else:
                        logger.error(f"划转失败: {coin} - 从 {transfer['from']} - 错误: {transfer['error']}")
                        
    elif args.command == "liquidate":
        async with AssetManager() as manager:
            results = await manager.liquidate_assets(args.target, args.slippage)
            
            for coin, orders in results.items():
                for order in orders:
                    if order["status"] == "success":
                        logger.success(f"清算成功: {coin} - 账户 {order['account']} - 数量 {order['amount']}")
                    else:
                        logger.error(f"清算失败: {coin} - 账户 {order['account']} - 错误: {order['error']}")
                        
if __name__ == "__main__":
    setup_logger()
    asyncio.run(main()) 